//
//  AsActivityDetailViewController.m
//  AttendenceSys
//
//  Created by ld on 16/3/1.
//  Copyright © 2016年 窦芳俊. All rights reserved.
//

#import "AsActivityDetailViewController.h"

@interface AsActivityDetailViewController ()

@end

@implementation AsActivityDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.strNavTitle = @"活动详情";
    //[self setRightButtonWithImageName:@"ic_collection" bgImageName:@""];
    [self initView];
    // Do any additional setup after loading the view.
}

-(void)initView
{
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-49-15);
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_tableView registerClass:[SchActivitiesSingeCell class] forCellReuseIdentifier:NSStringFromClass([SchActivitiesSingeCell class])];
    [self.view addSubview:_tableView];
    
    //立即参与
    UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0, singleCellHeight*6/5, CGRectGetWidth(self.view.bounds), 100)];
    footer.backgroundColor = [UIColor clearColor];
    
    _saveBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    _saveBtn.frame = CGRectMake(50, 50,[UIScreen mainScreen].bounds.size.width-50*2,50);
    
    //设置参与扫描按钮
    [self setSaveBtnShow];
    
    _saveBtn.layer.cornerRadius = 4.5;
    [_saveBtn addTarget:self action:@selector(immediateparticipation) forControlEvents:UIControlEventTouchUpInside];
    
    [_saveBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    //_saveBtn.backgroundColor = RGB(252, 120, 61);
    [footer addSubview:_saveBtn];
    _tableView.tableFooterView = footer;
}

//立即参与
-(void)immediateparticipation
{
    if ([_actDetailInfo.isInvited isEqualToString:@"0"]) {
        [self participateInactivities];
    }
    else
    {
        [self getScanView];
    }
    
}

//扫描
-(void)getScanView
{
    ASScanQRCodeViewController* scanViewCtrl = [[ASScanQRCodeViewController alloc] init];
        scanViewCtrl.hidesBottomBarWhenPushed = YES;
    scanViewCtrl.delegate = self;
    [self.navigationController pushViewController:scanViewCtrl animated:YES];
}

//点赞
//- (void)rightButtonPressed:(id)sender
//{
//    [self clickalikeForActivities];
//}


//活动点赞接口 http://121.42.185.124:8080/LawSchool/praiseFace.action?userCode=xiaohu&fkActionId=1 fkActionId活动ID
-(void)clickalikeForActivities
{
    NSString* refer = @"praiseFace.action?";
    NSString* prefix = kASHttpUrl(refer);
    
    NSString* inActUrl = [NSString stringWithFormat:@"%@userCode=%@&fkActionId=%@", prefix,AS_APP_UserCode,_actDetailInfo.pkActionId];
    
    [SVProgressHUD showWithStatus:@"点赞" maskType:SVProgressHUDMaskTypeClear];
    ASNetworkEngine *networkingEngine = [ASNetworkEngine sharedInstance];
    [networkingEngine GET:inActUrl parameters:nil success:^(id responseObject) {
        NSDictionary* jsonRsp = (NSDictionary *)responseObject;
        jsonRsp = [jsonRsp processDictionaryIsNSNull:jsonRsp];
        if (isSuccessRsp(jsonRsp))
        {
            [SVProgressHUD showErrorWithStatus:errorMsgRsp(jsonRsp)];
            [SVProgressHUD dismiss];
            
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:errorMsgRsp(jsonRsp)];
        }
    } failure:^(NSError *error) {
        //[SVProgressHUD showErrorWithStatus:error.description];
        [SVProgressHUD showErrorWithStatus:@"网络异常，请稍后再试"];
    }];
}

//活动参加接口 http://121.42.185.124:8080/LawSchool/inviteFace.action?userCode=xiaohu&fkActionId=1 fkActionId活动ID
-(void)participateInactivities
{
    NSString* refer = @"inviteFace.action?";
    NSString* prefix = kASHttpUrl(refer);
    
    NSString* inActUrl = [NSString stringWithFormat:@"%@userCode=%@&fkActionId=%@", prefix,AS_APP_UserCode,_actDetailInfo.pkActionId];
    
    [SVProgressHUD showWithStatus:@"立即参与" maskType:SVProgressHUDMaskTypeClear];
    ASNetworkEngine *networkingEngine = [ASNetworkEngine sharedInstance];
    [networkingEngine GET:inActUrl parameters:nil success:^(id responseObject) {
        NSDictionary* jsonRsp = (NSDictionary *)responseObject;
        jsonRsp = [jsonRsp processDictionaryIsNSNull:jsonRsp];
        if (isSuccessRsp(jsonRsp))
        {
            _actDetailInfo.isInvited = @"1";
            NSInteger invitedNum = [_actDetailInfo.allInvitedNumber integerValue];
            invitedNum += 1;
            _actDetailInfo.allInvitedNumber = [NSString stringWithFormat:@"%ld",(long)invitedNum];
            
            if (_delegate && [_delegate respondsToSelector:@selector(refershActList:)]) {
                [_delegate refershActList:_actDetailInfo];
            }
            
            [self.tableView reloadData];
            [_saveBtn setTitle:@"扫描签到" forState:UIControlStateNormal];
            
            [SVProgressHUD showErrorWithStatus:errorMsgRsp(jsonRsp)];
            [SVProgressHUD dismiss];
            
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:errorMsgRsp(jsonRsp)];
        }
    } failure:^(NSError *error) {
        //[SVProgressHUD showErrorWithStatus:error.description];
        [SVProgressHUD showErrorWithStatus:@"网络异常，请稍后再试"];
    }];
}


#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SchActivitiesSingeCell* cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([SchActivitiesSingeCell class])];
    
    [cell setBackgroundColor:[UIColor clearColor]];
    cell.nameLab.text = _actDetailInfo.userName;
    cell.timeLab.text = @"";
    cell.descLab.text = _actDetailInfo.actionDesc;
    
    if (0 < _actDetailInfo.imageUrlArr.count)
    {
        [cell initScrollView:_actDetailInfo.imageUrlArr];
        cell.descLab.frame = CGRectMake(cell.descLab.frame.origin.x,
                                        cell.descLab.frame.origin.y,
                                        cell.descLab.frame.size.width,
                                        50);
    }
    else
    {
        cell.descLab.frame = CGRectMake(cell.descLab.frame.origin.x,
                                        cell.descLab.frame.origin.y,
                                        cell.descLab.frame.size.width,
                                        singleCellHeight-35-(cell.actionTitleLab.frame.size.height+60));
    }
    
    cell.scanSignLab.text = [NSString stringWithFormat:@"报名参加人数: %@",_actDetailInfo.allInvitedNumber];
    cell.attendLab.text = [NSString stringWithFormat:@"扫码签到人数: %@",_actDetailInfo.allCheckedNumber];
    if (!_actDetailInfo.actionTitle)
    {
        _actDetailInfo.actionTitle = @"";
    }
    
    cell.actionTitleLab.text = [NSString stringWithFormat:@"活动标题: %@",_actDetailInfo.actionTitle];
//    cell.favorateNumLab.text = _actDetailInfo.favorateNum;
    [cell.headImageBtn setImageWithURL:_actDetailInfo.userPic placeholderImage:[UIImage imageNamed:@"portrait_default"]];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    [cell initActDetailInfoView];
    
    if (!_actDetailInfo.actionTime)
    {
        _actDetailInfo.actionTime = @"";
        cell.detailTime.text = @"";
    }
    else
    {
        if ([_actDetailInfo.actionTime length] == 19)
        {
            cell.detailTime.text = [NSString stringWithFormat:@"活动时间：%@",
                                    [_actDetailInfo.actionTime substringToIndex:([_actDetailInfo.actionTime length]-3)]];
        }
        else
        {
            cell.detailTime.text = [NSString stringWithFormat:@"活动时间：%@", _actDetailInfo.actionTime];
        }
    }
    
    if (!_actDetailInfo.sponsor) {
        _actDetailInfo.sponsor = @"";
    }
    
    if (!_actDetailInfo.actionArea) {
        _actDetailInfo.actionArea = @"";
    }
    
    cell.sponsorLab.text = [NSString stringWithFormat:@"主办方：%@",_actDetailInfo.sponsor];;
    cell.areaLab.text = [NSString stringWithFormat:@"地点：%@",_actDetailInfo.actionArea];
    cell.voteNumLab.text = [NSString stringWithFormat:@"%@人感兴趣",_actDetailInfo.voteNum];
    //[cell initfavHeadScrollView:_actDetailInfo.imageUrlArr];
    
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return singleCellHeight*6/5;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)setSaveBtnShow
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    if (16 < _actDetailInfo.actionTime.length)
    {
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    }
    else
    {
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    }
    NSDate *activityDate = [dateFormatter dateFromString:_actDetailInfo.actionTime];
    if (nil ==  activityDate)
    {
        // 活动时间格式有问题 禁用
        [_saveBtn setTitle:@"立即参与" forState:UIControlStateNormal];
        _saveBtn.backgroundColor = [UIColor grayColor];
        _saveBtn.enabled = NO;
        return;
    }
    
    NSDate* now = [NSDate date];
    if ([now compare:activityDate] > 0)
    {
//        // 进入即表示当前时间已经超过活动开始时间了，但是半小时内有效
//        if ([now timeIntervalSinceDate:activityDate] < 1500)
//        {
//        }
//        else
//        {
//            [_saveBtn setTitle:@"立即参与" forState:UIControlStateNormal];
//            _saveBtn.backgroundColor = [UIColor grayColor];
//            _saveBtn.enabled = NO;
//            return;
//        }
        
        [_saveBtn setTitle:@"立即参与" forState:UIControlStateNormal];
        _saveBtn.backgroundColor = [UIColor grayColor];
        _saveBtn.enabled = NO;
        return;
    }
    
    //_saveBtn.backgroundColor = RGB(252, 120, 61);
    _saveBtn.enabled = YES;
    if ([_actDetailInfo.isInvited isEqualToString:@"0"] && [_actDetailInfo.isCheck isEqualToString:@"0"])
    {
        _saveBtn.backgroundColor = RGB(252, 120, 61);
        [_saveBtn setTitle:@"立即参与" forState:UIControlStateNormal];
    }
    else if ([_actDetailInfo.isInvited isEqualToString:@"1"] && [_actDetailInfo.isCheck isEqualToString:@"0"])
    {
        _saveBtn.backgroundColor = RGB(252, 120, 61);
        [_saveBtn setTitle:@"扫描签到" forState:UIControlStateNormal];
    }
    else if ([_actDetailInfo.isInvited isEqualToString:@"1"] && [_actDetailInfo.isCheck isEqualToString:@"1"])
    {
        [_saveBtn setTitle:@"立即参与" forState:UIControlStateNormal];
        _saveBtn.backgroundColor = [UIColor grayColor];
        _saveBtn.enabled = NO;
    }
    else
    {
        _saveBtn.backgroundColor = RGB(252, 120, 61);
        [_saveBtn setTitle:@"立即参与" forState:UIControlStateNormal];
    }
}

//扫描签到OK
-(void)scanOk
{
    [_saveBtn setTitle:@"立即参与" forState:UIControlStateNormal];
    _saveBtn.backgroundColor = [UIColor grayColor];
    _saveBtn.enabled = NO;
    
    NSInteger checkNum = [_actDetailInfo.allCheckedNumber integerValue];
    checkNum += 1;
    _actDetailInfo.allCheckedNumber = [NSString stringWithFormat:@"%ld",(long)checkNum];
    
    if (_delegate && [_delegate respondsToSelector:@selector(refershActList:)]) {
        [_delegate refershActList:_actDetailInfo];
    }
    
    [self.tableView reloadData];
}

//颜色转换 背景图片
- (UIImage *)imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

@end
